package com.repro.lib.imageload

import android.app.Application
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.annotation.DrawableRes
import androidx.viewbinding.BuildConfig
import coil.Coil
import coil.ImageLoader
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.decode.SvgDecoder
import coil.decode.VideoFrameDecoder
import coil.fetch.VideoFrameFileFetcher
import coil.fetch.VideoFrameUriFetcher
import coil.request.CachePolicy
import coil.util.CoilUtils
import coil.util.DebugLogger
import com.repro.lib.imageload.impl.GlideEngine
import okhttp3.Cache
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import java.io.File

/**
 * 使用说明https://coil-kt.github.io/coil/image_pipeline/
 */
object ImageManager {
    //默认使用Gilded
    var mImageEngine: ImageEngine = GlideEngine.get()

    //默认无错误占位图
    @DrawableRes
    var errorImage: Int = 0//错误占位图

    //默认无占位图
    @DrawableRes
    var placeholder: Int = 0//占位图

    /**
     * coil 初始化创建imageLoad配置参数
     */
    @JvmStatic
    fun newImageLoader(
        application: Application,
        @DrawableRes errorImage: Int?,
        @DrawableRes placeholder: Int?
    ): ImageLoader {
        val imageLoader = ImageLoader.Builder(application)
        imageLoader.availableMemoryPercentage(0.25)
        imageLoader.memoryCachePolicy(CachePolicy.ENABLED)//启用内存缓存 默认三级缓存全部可读可写
        imageLoader.diskCachePolicy(CachePolicy.ENABLED)
        imageLoader.networkCachePolicy(CachePolicy.ENABLED)
        imageLoader.componentRegistry {
            // GIFs
            if (Build.VERSION.SDK_INT >= 28) {
                add(ImageDecoderDecoder(application))
            } else {
                add(GifDecoder(true))
            }
            // SVGs
            add(SvgDecoder(application))
            // Video frames
            add(VideoFrameDecoder(application))
            add(VideoFrameFileFetcher(application))
            add(VideoFrameUriFetcher(application))
        }
        imageLoader.okHttpClient {
            // Don't limit concurrent network requests by host.
            val dispatcher = Dispatcher().apply { maxRequestsPerHost = maxRequests }
            // Lazily create the OkHttpClient that is used for network operations.
            OkHttpClient.Builder()
                .cache(CoilUtils.createDefaultCache(application))
//                .cache(createDefaultCache(application))
                .dispatcher(dispatcher)
                .build()
        }
        imageLoader.crossfade(true)
        imageLoader.apply {
            if (BuildConfig.DEBUG) {
                Log.d("CoilImageLoader", DebugLogger(Log.VERBOSE).toString())
            }
        }
        if (errorImage != null && errorImage != 0) {
            imageLoader.error(errorImage)
        }
        if (placeholder != null && placeholder != 0) {
            imageLoader.placeholder(placeholder)
        }
        return imageLoader.build()
    }

    /**
     * 创建默认缓存10M
     */
    private fun createDefaultCache(context: Context): Cache {
        val cacheDirectory = getDefaultCacheDirectory(context)
        return Cache(cacheDirectory, 10 * 1024 * 1024)
    }

    /**
     * 默认缓存路径
     */
    private fun getDefaultCacheDirectory(context: Context): File {
        return File(context.cacheDir, "image_cache").apply { mkdirs() }
    }

    /**
     * 初始化
     */
    fun initImageLoadOption(
        application: Application,
        @DrawableRes errorImage: Int = 0,
        @DrawableRes placeholder: Int = 0,
        imageEngineType: ImageEngine = GlideEngine.get()
    ) {
        this.mImageEngine = imageEngineType
        this.errorImage = errorImage
        this.placeholder = placeholder
        Coil.setImageLoader(newImageLoader(application, errorImage, placeholder))
    }
}